/*
 *  Copyright 2012 Alexey Andreev.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ru.justplay.battleship;

import org.nop.core.AbstractController;
import org.nop.core.Content;
import org.nop.core.RouteBinding;
import org.nop.util.Injected;
import ru.justplay.battleship.view.CreateGameView;
import ru.justplay.battleship.view.GameView;
import ru.justplay.battleship.view.WelcomeView;
import ru.justplay.battleship.view.WrongInvitationView;
import ru.justplay.core.api.GameInformation;
import ru.justplay.core.api.GameManager;
import ru.justplay.core.api.PlayerInformation;
import ru.justplay.core.api.SessionInformation;

/**
 *
 * @author Alexey Andreev
 */
@RouteBinding(BattleshipRoute.class)
public class BattleshipController extends AbstractController {
    private GameManager gameManager;

    @Injected
    public BattleshipController(GameManager gameManager) {
        this.gameManager = gameManager;
    }

    public Content main() {
        return html(createView(WelcomeView.class));
    }

    public Content createGame() {
        GameInformation info = gameManager.createGame("battleship");
        return html(createView(CreateGameView.class)
                .setInvitations(info.getInvitations()));
    }

    public Content invitation(String token) {
        PlayerInformation player = gameManager.useInvitation(token);
        if (player == null) {
            return html(createView(WrongInvitationView.class));
        }
        return redirect(route(BattleshipRoute.class)
                .game(player.getGameId(), player.getPasswordToken()));
    }

    public Content game(long gameId, String secret) {
        SessionInformation session = gameManager.getSessionInformation(gameId);
        if (session == null) {
            return null;
        }
        return html(createView(GameView.class)
                .setSessionId(session.getSessionId())
                .setNodeId(session.getNodeId())
                .setActorId(session.getActorId())
                .setSecret(secret));
    }
}
